<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: ad_rating_fields.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * This is the admin interface for the rating configuration of the Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage admin
 * @version $Id: ad_rating_fields.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

if ( ! defined( 'AD_REGISTRY_CALLED' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

/**#@+
 * Fusion Registry requires
 */
require_once(AD_REGISTRY_PATH.'ad_registry_loader.php');
require_once(REGISTRY_PATH.'lib/ratings.php');
/**#@-*/

/**
 * Class ad_registry_ratings deals with rating configuration of the Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage admin
 */
class ad_registry_rating_fields
{
    var $ipsclass;

    /** @var string */
    var $base_url;

    /** @var object */
    var $ad_registry_loader;

    /** @var array */
    var $lib = array();

    /**
     * Intialization of ad_registry_ratings
     *
     * Another traffic cop function, there should be minimal procedural code
     * here.
     *
     * @global array
     */
    function auto_run()
    {
        // Kill globals
        $tmp_in = array_merge( $_GET, $_POST, $_COOKIE );

        foreach ( $tmp_in as $k => $v )
        {
            unset($$k);
        }

        // Initialize ad_registry_loader object
        $this->ad_registry_loader = new ad_registry_loader();
        $this->ad_registry_loader->ipsclass =& $this->ipsclass;
        $this->ad_registry_loader->auto_run(&$this);

        $this->lib['rating_fields'] = new registry_ratings(&$this);
        $this->lib['rating_fields']->ipsclass =& $this->ipsclass;

        switch($this->ipsclass->input['code'])
        {
            case 'new':
                $this->do_form('new');
                break;
            case 'donew':
                $this->do_new();
                break;
            //-----------------------------------------
            case 'edit':
                $this->do_form('edit');
                break;
            case 'doedit':
                $this->do_edit();
                break;
            //-----------------------------------------
            case 'delete':
                $this->do_delete();
                break;
            //-----------------------------------------
            case 'config':
                $this->save_config();
                break;

            default:
                $this->main_menu();
                break;
        }
    }


    /**
     * Delete rating field
     */
    function do_delete()
    {
        $this->ipsclass->input['r'] = intval($this->ipsclass->input['r']);

        if ( ! $this->ipsclass->input['r'] )
        {
            $this->ipsclass->admin->error("Could not determine the source rating field ID.");
        }

        // Grab current info
        $rating = $this->ipsclass->DB->simple_exec_query( array( 'select' => '*', 'from' => 'registry_rating_defs', 'where' => 'rating_id='.$this->ipsclass->input['r'] ) );

        if ($rating['rating_id'] == "")
        {
            $this->ipsclass->admin->error("Could not retrieve the rating field data based on ID {$this->ipsclass->input['r']}");
        }

        // Delete the field definition
        $this->ipsclass->DB->simple_exec_query( array( 'delete' => 'registry_rating_defs', 'where' => "rating_id=".$this->ipsclass->input['r'] ) );

        // Delete any votes...
        $this->ipsclass->DB->simple_exec_query( array( 'delete' => 'registry_rating_entries', 'where' => "rating_id=".$this->ipsclass->input['r'] ) );

        // Delete any reports...
        $this->ipsclass->DB->simple_exec_query( array( 'delete' => 'registry_rating_reports', 'where' => "rating_id=".$this->ipsclass->input['r'] ) );

        $this->ipsclass->admin->save_log("Fusion Registry Rating Field '{$rating['rating_name']}' removed");

        $this->ipsclass->admin->done_screen("Fusion Registry Rating Field '{$rating['rating_name']}' removed", "Fusion Registry Rating Fields", "act=".REGISTRY_URL."&section=components&menu=rating_fields", 'redirect' );
    }


    /**
     * Save the changes made to a rating field
     */
    function do_edit()
    {
        $this->ipsclass->input['rating_name'] = trim($this->ipsclass->input['rating_name']);

        if ($this->ipsclass->input['rating_name'] == "")
        {
            $this->ipsclass->admin->error("You must enter a Custom Field name");
        }

        $this->ipsclass->DB->do_update( 'registry_rating_defs',
                                        array( 'rating_name'  => $this->ipsclass->input['rating_name'],
                                               'rating_order' => $this->ipsclass->input['rating_order'], ),
                                        "rating_id={$this->ipsclass->input['r']}" );

        $this->ipsclass->admin->save_log("Fusion Registry Rating Field '{$this->ipsclass->input['rating_name']}' edited");

        $this->ipsclass->admin->done_screen("Fusion Registry Rating Field '{$this->ipsclass->input['rating_name']}' edited", "Fusion Registry Rating Fields", "act=".REGISTRY_URL."&section=components&menu=rating_fields", 'redirect' );
    }


    /**
     * Display HTML form for adding or editing a rating field
     *
     * If $type is 'edit' we query for the current data to populate
     * into the HTML form.
     *
     * @param string $type Pass in 'edit' to query for existing data, any other value will show form for adding new rating field
     */
    function do_form($type='edit')
    {
        if ( $type == 'edit' )
        {
            if ($this->ipsclass->input['r'] == "")
            {
                $this->ipsclass->admin->error("You didn't choose a rating field to edit, duh!");
            }

            // Go get our Custom Field definition
            $rating_data = $this->lib['rating_fields']->get_rating_defs( array( 'WHERE' => 'rating_id='.$this->ipsclass->input['r'] ) );

            // Since get_rating_defs() returns an array of arrays, we are removing a layer here.
            //   The key is the rating_id which was passed in from the beginning ;)
            $rating = $rating_data[$this->ipsclass->input['r']];

            if ($rating['rating_id'] == "")
            {
                $this->ipsclass->admin->error("Could not retrieve the rating field data based on ID {$this->ipsclass->input['r']}");
            }

            $title  = "Editing Rating Field: {$rating['rating_name']}";
            $code   = "doedit";
        }
        else
        {
            $title  = "Add a Rating Field";
            $code   = "donew";
        }

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( $title, "This section will allow you to add or edit an existing rating field.".'<br />&nbsp;' ) . "<br >";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code                 ),
                                                                             2 => array( 'act' , REGISTRY_URL          ),
                                                                             3 => array( 'r'   , $this->ipsclass->input['r'] ),
                                                                             4 => array( 'menu', 'rating_fields'             ),
                                                                             5 => array( 'section', 'components'       ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "40%" );
        $this->ipsclass->adskin->td_header[] = array( "{none}"  , "60%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( $title );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Rating Name</b>" ,
                                                                             $this->ipsclass->adskin->form_input("rating_name", $rating['rating_name'])
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Order</b>" ,
                                                                             $this->ipsclass->adskin->form_input("rating_order", $rating['rating_order'])
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        if ( $type == 'edit' )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Edit this Rating Field");
        }
        else
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->end_form_standalone("Create this Rating Field");

            $this->ipsclass->html .= $this->ipsclass->adskin->end_table();
        }

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=rating_fields', 'Fusion Registry Rating Fields' );
        $this->ipsclass->admin->nav[] = array( '', 'Add/Edit Rating Field' );

        $this->ipsclass->admin->output();
    }


    /**
     * Create new rating field
     */
    function do_new()
    {
        $this->ipsclass->input['rating_name'] = trim($this->ipsclass->input['rating_name']);

        if ($this->ipsclass->input['rating_name'] == "")
        {
            $this->ipsclass->admin->error("You must enter a Rating Field name");
        }

        $this->ipsclass->DB->do_insert( 'registry_rating_defs',
                                        array (
                                                'rating_name'  => $this->ipsclass->input['rating_name'],
                                                'rating_order' => $this->ipsclass->input['rating_order'],
                                      )       );

        $this->ipsclass->admin->save_log("Fusion Registry Rating Field '{$this->ipsclass->input['rating_name']}' created");

        $this->ipsclass->admin->done_screen("Fusion Registry Rating Field '{$this->ipsclass->input['rating_name']}' created", "Fusion Registry Rating Fields", "act=".REGISTRY_URL."&section=components&menu=rating_fields", 'redirect' );
    }


    /**
     * Display Fusion Registry Rating Configuration Screen
     */
    function main_menu()
    {
        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Fusion Registry Rating Configuration", "You may update your Fusion Registry Rating Configuration below.".'<br />&nbsp;' ) . "<br >";

        //------------------------------
        // Fusion Registry Configuration form
        //------------------------------
        $code = "config";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code      ),
                                                                             2 => array( 'act' , REGISTRY_URL ),
                                                                             3 => array( 'menu', 'rating_fields'  ),
                                                                             4 => array( 'section', 'components' ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "Option"  , "40%" );
        $this->ipsclass->adskin->td_header[] = array( "Value" , "60%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Fusion Registry Rating Options" );

        // Build the Config HTML
        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Enable Item Ratings?</b><div style='color:gray'>Turns on/off the rating system for items in the Registry.</div>",
                                                                             $this->ipsclass->adskin->form_yes_no('enable_item_ratings', $this->registry_config['enable_item_ratings']),
                                                                    )      );

        /*$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Enable Modification Ratings?</b><div style='color:gray'>Turns on/off the rating system for modifications in the Registry.</div>",
                                                                             $this->ipsclass->adskin->form_yes_no('enable_mod_ratings', $this->registry_config['enable_mod_ratings']),
                                                                    )      );*/

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Rating Value Range?</b><div style='color:gray'>Represents the worst/best rating values. Example: 0 to 10</div><br/><br/><b>WARNING:</b> Changing this value could cause old ratings to be incorrectly weighed. This won't cause a huge problem, but overall ratings will be a little incorrect until more votes are cast.",
                                                                             "Minimum: &nbsp;". $this->ipsclass->adskin->form_input('rating_min', $this->registry_config['rating_min'])."<br/>".
                                                                             "Maximum: ". $this->ipsclass->adskin->form_input('rating_max', $this->registry_config['rating_max']),
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Minimum number of votes required for statistics?</b><div style='color:gray'>Items with less than this amount of total votes will not be shown in any statistics, such as the top rated items.</div>",
                                                                             $this->ipsclass->adskin->form_input('rating_min_stats', $this->registry_config['rating_min_stats']),
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Save");

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        // Break it up ;)
        $this->ipsclass->html .= '<br /><br />';

        // Rating types
        $this->ipsclass->adskin->td_header[] = array( "Edit"     , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Delete"   , "6%"  );
        $this->ipsclass->adskin->td_header[] = array( "Name"     , "82%" );
        $this->ipsclass->adskin->td_header[] = array( "Order"    , "6%" );

        $this->ipsclass->html .=
        "<script type='text/javascript'>
            <!--
            function confirm_delete_rating( rating_id )
            {
                if ( confirm('Are you sure you want to delete this Fusion Registry Rating field and all votes associated with it? This operation is not undo-able!') )
                {
                    window.location.href = '{$this->ipsclass->base_url}&act={REGISTRY_URL}&section=components&menu=rating_fields&code=delete&r=' + rating_id;
                }
            }
            // -->
        </script> ";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Fusion Registry Rating Fields" );

        // Grab all the rating definitions
        $rating_defs = $this->lib['rating_fields']->get_rating_defs( array( 'ORDER BY' => 'rating_order ASC, rating_name ASC' ) );

        // Loop through our custom field definitions we got from up above
        foreach ( $rating_defs as $rating_id => $rating_row )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center><a href="'.$this->ipsclass->base_url.'&amp;act='.REGISTRY_URL.'&section=components&menu=rating_fields&amp;code=edit&amp;r='.$rating_row['rating_id'].'">'. $this->ad_registry_loader->imgs['edit'] .'</a></center>',
                                                                                 '<center><a href="javascript:confirm_delete_rating( '.$rating_row['rating_id'].' )">'. $this->ad_registry_loader->imgs['delete'] .'</a></center>',
                                                                                 $rating_row['rating_name'],
                                                                                 $rating_row['rating_order'],
                                                                        )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $html = $this->ipsclass->adskin->js_make_button("Add New Rating Field", $this->ipsclass->base_url."&amp;act=".REGISTRY_URL."&section=components&menu=rating_fields&amp;code=new");

        $this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($html, 'left');

        $this->ipsclass->html .= '<br /><br />';

        // That's all folk!
        $this->ipsclass->admin->output();
    }


    /**
     * Save the Fusion Registry Rating Configuration
     */
    function save_config()
    {
        $config_list = array( 'enable_item_ratings',
                              'enable_mod_ratings',
                              'rating_min',
                              'rating_max',
                              'rating_min_stats',
                            );

        $config_array = array();

        // Loop through and update/insert config options
        foreach ( $config_list as $config_name )
        {
            $config_array[ $config_name ] = $this->ipsclass->input[ $config_name ];
        }

        $this->ad_registry_loader->update_config($config_array);

        $text = 'Updated Fusion Registry Rating Config';
        $url = 'act='.REGISTRY_URL.'&section=components&menu=rating_fields';
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }
}
?>